package com.zlk.algorithm.huawei.leetcode.array;

import org.junit.Test;

import java.util.Arrays;

/**
 * @program: algorithm
 * @ClassName Code08_merge
 * @description:
 * 以数组 intervals 表示若干个区间的集合，其中单个区间为
 * intervals[i] = [starti, endi] 。请你合并所有重叠的区间，
 * 并返回 一个不重叠的区间数组，该数组需恰好覆盖输入中的所有区间
 * @author: slfang
 * @create: 2025-01-03 10:22
 * @Version 1.0
 **/
public class Code08_merge {

    public int[][] merge(int[][] intervals) {
        int n = intervals.length;
        int m = intervals[0].length;
        Arrays.sort(intervals,(a,b)->
                a[0]==b[0]?a[1]-b[1]:a[0]-b[0]
        );
        int[][] ans = new int[n][m];
        ans[0] = intervals[0];
        int preEnd = intervals[0][1];
        int index = 0;
        for (int i = 1; i < n; i++) {
            if(intervals[i][0]>preEnd){
                ans[++index] = intervals[i];
            }else{
                ans[index][1]=Math.max(ans[index][1],intervals[i][1]);
            }
            preEnd = ans[index][1];
        }
        //int[][] copyAns = new int[index+1][2];
        return Arrays.copyOfRange(ans,0,index+1);

    }

    @Test
    public void test(){
        int[][] params= new int[7][2];
        params[0] = new int[]{2,3};
        params[1] = new int[]{2,2};
        params[2] = new int[]{3,3};
        params[3] = new int[]{1,3};
        params[4] = new int[]{5,7};
        params[5] = new int[]{2,2};
        params[6] = new int[]{4,6};
        int[][] merge = merge(params);
        Arrays.toString(merge);
    }
}
